﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
using Coding4Fun.Phone.Controls;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
using System.Diagnostics;
using Qplus.enums;
using Qplus.Infrastructure;
using Qplus.protocol;
using Qplus.UI;
using System.Threading;
using Qplus.Commands;
using Newtonsoft.Json.Linq;
using Qplus.beans;

namespace Qplus
{
    public partial class MainPage : PhoneApplicationPage
    {
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            //enterBtn.AddHandler(Button.MouseLeftButtonDownEvent, new MouseButtonEventHandler(this.Button_MouseLeftButtonDown), true);
            //enterBtn.MouseMove += Button_MouseMove;
            //enterBtn.AddHandler(Button.MouseLeftButtonUpEvent, new MouseButtonEventHandler(this.Button_MouseLeftButtonUp), true);
        }

        #region MOVE enterBtn
//MOVE
        CompositeTransform transform;
        private void enterBtn_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            enterBtn.Click += enterBtn_Click;
        }
        private void enterBtn_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            ButtonEx tmpBtn = sender as ButtonEx;
            transform = tmpBtn.RenderTransform as CompositeTransform;

            #region  缩放操作
            //if (e.DeltaManipulation.Scale.X > 0 || e.DeltaManipulation.Scale.Y > 0)
            //{
            //    double maxScale = Math.Max(e.DeltaManipulation.Scale.X, e.DeltaManipulation.Scale.Y);
            //    transform.ScaleX *= maxScale;
            //    transform.ScaleY *= maxScale;
            //}
            #endregion
            //移动操作
            transform.TranslateX += e.DeltaManipulation.Translation.X;
            transform.TranslateY += e.DeltaManipulation.Translation.Y;

            //postionInfo.Text = "当前偏移量：X:" + transform.TranslateX.ToString() + " Y:" + transform.TranslateY.ToString() + " 半径:" + (ellipse.ActualWidth / 2).ToString();
            // 表示该事件已经被处理，不要再执行后面的处理函数
            e.Handled = true;

            if (System.Math.Abs(e.DeltaManipulation.Translation.X) > 0 || System.Math.Abs(e.DeltaManipulation.Translation.Y) > 0)
            {
                enterBtn.Click -= enterBtn_Click;
            }
        }
        private void enterBtn_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            ButtonEx tmpBtn = sender as ButtonEx;
            transform = tmpBtn.RenderTransform as CompositeTransform;

            if (transform.TranslateX > 0) transform.TranslateX = 0;
            else if (transform.TranslateX < (114 - 480)) transform.TranslateX = 114 - 480;
            if (transform.TranslateY > (768 - 116)) transform.TranslateY = 768 - 116;
            else if (transform.TranslateY < 0) transform.TranslateY = 0;
            #region NOTUSE
            //else
            //{
            //    DispatcherTimer DelayedTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
            //    DelayedTimer.Tick += (s, e0) =>
            //    {
            //        //perform action
            //        DelayedTimer.Stop();
            //        enterBtn.Click += enterBtn_Click;
            //    };
            //    DelayedTimer.Start();
            //}
            #endregion
        }
//CLICK
        private void enterBtn_Click(object sender, RoutedEventArgs e)
        {
            //checkNet();
            waitBar.Visibility = System.Windows.Visibility.Visible;
            QplusT.getInstance().login();
            LoginLogout.Instance.loginEvent += new EventHandler<UIEvent>(Instance_loginEvent);
        }

        void Instance_loginEvent(object sender, UIEvent e)
        {
            //throw new NotImplementedException();
            if (QplusT.Instance.IsFirstLog)
            {
                GetUserListCommand command = new GetUserListCommand(QUser.Instance.userID, QUser.Instance.key);
                command.MessageReceivedFromHttpServer += new EventHandler<MessageReceivedFromServer>(GetUserListCommand_MessageReceivedFromHttpServer);
                command.set(0);
                command.execute(QplusT.Instance.getUser().url);
            }
        }

        void GetUserListCommand_MessageReceivedFromHttpServer(object sender, MessageReceivedFromServer e)
        {
            //throw new NotImplementedException();
            try
            {
                QUser.Instance.FriendList = JObject.Parse(e.strMessage);
                UIData.Instance.userList.update(QUser.Instance.FriendList);
            }
            catch { }

            GetRoomListCommand command = new GetRoomListCommand(QUser.Instance.userID.ToString(), System.Text.Encoding.UTF8.GetString(QUser.Instance.key, 0, QUser.Instance.key.Length));
            command.MessageReceivedFromHttpServer += GetRoomListCommand_MessageReceivedFromServer;
            command.set(0);
            command.execute(QUser.Instance.url);
        }
        void GetRoomListCommand_MessageReceivedFromServer(object sender, MessageReceivedFromServer e)
        {
            //throw new NotImplementedException();
            try
            {
                QUser.Instance.RoomList = JObject.Parse(e.strMessage);
            }
            catch { }
            gotoEntryPage();
        }
        private void gotoEntryPage()
        {
            Dispatcher.BeginInvoke(() =>
            {
                waitBar.Visibility = System.Windows.Visibility.Collapsed;
                NavigationService.Navigate(new Uri("/UI/EntryPage.xaml", UriKind.Relative));
            });
        }
#if fause
        void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            using (var reader = new System.IO.StreamReader(e.Result))
            {
                MessageBox.Show(reader.ReadToEnd());
            }
            NavigationService.Navigate(new Uri("/UI/EntryPage.xaml", UriKind.Relative));
        }
        private void OnMessageReceivedCompleted(object sender, MessageReceivedFromServer e)
        {
            //var socket=sender as TcpSocket;

            //switch (socket.msgfromS.MsgID)
            //{
            //    case MMessageID.L2C_RESP_LOGIN:
            //        {
                        //loginUServer();
                        //UI.UIData.Instance.GetUserList(0);
                        //UI.UIData.Instance.httpCMD.MessageReceivedFromServer += httpCMD_MessageReceivedFromServer;
                        ////UI.UIData.Instance.GetRoomList(0);
                        ////UIData.Instance.httpCMD.MessageReceivedFromServer += httpCMD_MessageReceivedFromServer;
                        //startKeepAlive();
            //            break;
            //        }
            //    case MMessageID.U2C_RESP_LOGIN:
            //        {
            //            startKeepAlive();
            //            break;
            //        }
            //    default:
            //        break;
            //}
        }
#endif
#if fause
        private void ProcessIncomingMessage()
        {
            byte[] ReceivedMessage=new byte[1];
            // Future hook for handling the message in somewhere else.
            // It's most probably wise to put the parsing logic in some other class.
            if (MessageReceivedFromServer != null)
                MessageReceivedFromServer(this, new MessageReceivedFromServer(ReceivedMessage));
        }
        private bool networkIsAvailable;
        private Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType _currentNetworkType; //网络连接的类型
        private bool checkNet()
        {
            bool result = false;
            networkIsAvailable = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();//当前网络是否可用
            _currentNetworkType = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType;//获取当前网络的类型

            ///if (networkIsAvailable)
            ///{
            ///    //return "Network Available";
            ///    //Message.Text = "联网状态";
            ///    //Message.Background = new SolidColorBrush(Colors.Green);
            ///}
            ///else
            ///{
            ///    MessageBox.Show("Network unAvailable");
            ///    return "";// "Network unAvailable";
            ///    //Message.Text = "断网状态";
            ///    //Message.Background = new SolidColorBrush(Colors.Red);
            ///}

            switch (_currentNetworkType){
            
                case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandCdma:
                    {
                        //Cdma网络
                        break;
                    }
                case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandGsm:
                    {
                        //Csm网络
                        break;
                    }
                case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Wireless80211:
                    {
                        //Wireless网络
                        break;
                    }
                case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet:
                    {
                        //Ethernet网络
                        break;
                    }
                case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None:
                    {
                        //网络不可用
                        result = false;
                        break;
                    }
                default:
                    //其他的网络
                    break;
            }
            return result;
        }

        void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            //throw new NotImplementedException();
            //_BasePage.BackKeyPress -= BasePage_BackKeyPress;
            Debug.WriteLine("@@");
        }
        void bw_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            //throw new NotImplementedException();
            //if (pc.IsShown)
            //{
            //    pc.Close();
            //}
            //else
            //{
            //    NavigationService.StopLoading();
            //}
        }
#endif
#if false
        private void enterBtn_Click(object sender, RoutedEventArgs e)
        {   
            if (iswaiting == false)
            {
                Boolean res = QplusT.getInstance().loginVerify(ipAddr, version, E_LOGIN_TYPE.ELT_DEVICE,
                        deviceID, "", appID, appVer);

                KeepAlive.getInstance().startKeepAlive();

                //PopupContainer pc = new PopupContainer(this);
                //WaitControl waitCtrl = new WaitControl();
                //pc.Show(waitCtrl);
                WaitControl waitCtrl = new WaitControl() { VerticalAlignment = System.Windows.VerticalAlignment.Bottom};
                LayoutRoot.Children.Add(waitCtrl);
                DispatcherTimer DelayedTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(5) };
                DelayedTimer.Tick += (s, e0) =>
                {
                    //perform action
                    DelayedTimer.Stop();
                    iswaiting = false;
                    LayoutRoot.Children.Remove(waitCtrl);
                    NavigationService.Navigate(new Uri("/UI/EntryPage.xaml", UriKind.Relative));
                };
                DelayedTimer.Start();
                iswaiting = true;
            }
        }
#endif
        #endregion
    }
}